package com.qys.livesMall.security.interceptor.core;

import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.thread.ThreadContext;
import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.common.utils.QysStringUtils;
import com.qys.livesMall.user.service.ISysRoleMenuService;
import com.qys.livesMall.framework.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

@Order(5)
public class SecurityInterceptor implements HandlerInterceptor {

    private static Log logger = LogFactory.getLog(LoginInterceptor.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;

    //handle 前

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("***********************资源拦截器*************************");
        //如果是登录请求，跳过验证
        String url = request.getRequestURI();

        //文件上传不需要权限校验
        if (url.contains("/api/app/common/upload")) {
            return true;
        }

        //超级管理员直接放过
        LoginUser user = ThreadContext.getUser();
        if (SecurityUtils.isAdmin(user.getUserId())) {
            return true;
        }

        R jsonResult = null;
        boolean pass = true;
//        //ip验证
//        String ip=IpUtil.getIpAddr(request);
//        boolean ipExist=ipConfigService.isExist(ip);
//        if (!ipExist){
//            //未登陆向前端返回数据
//            jsonResult = Result.fail("402","无效地址");
//            pass=false;
//        }
       Set<String> permissions = iSysRoleMenuService.getPermissionCache(user.getUserId());
        boolean isInclude = QysStringUtils.matches(url, permissions);
       if (pass && !isInclude) {
            //未登陆向前端返回数据
            jsonResult = R.fail("402", "无权访问资源");
            pass = false;
        }
        if (!pass) {
            String jsonString = JSONObject.toJSONString(jsonResult);
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            try {
                writer = response.getWriter();
                writer.print(jsonString);

            } catch (IOException e) {
                logger.info("无权访问资源", e);
            } finally {
                if (writer != null)
                    writer.close();
            }
            return false;
        }
        //user.getUserId()
        return true;
    }


}
